<!-- 业务配置 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<el-form :model="searchFormData" :inline="true" :label-width="100">
			<el-form-item label="系统名称" prop="systemCode">
				<yd-select
					v-model="searchFormData.systemCode"
					:config="{
						placeholder: '请选择系统名称',
						api: { name: 'queryAllAppSystemOptions', params: {} },
						selectKey: 'code',
						selectFirst: true,
						allOption: false,
						multiple: false,
					}"
					@selectInited="formInited"
				></yd-select>
			</el-form-item>
			<el-form-item label="业务名称" prop="name">
				<el-input v-model="searchFormData.name" placeholder="请输入业务名称" clearable class="yd-input" />
			</el-form-item>
			<el-form-item label="步骤设置" prop="stepSet">
				<yd-select
					v-model="searchFormData.stepSet"
					:config="{
						placeholder: '请选择步骤设置',
						data: options.stepSetOptions,
						selectKey: 'value',
						allOption: false,
						multiple: false,
						clearable: true,
					}"
				></yd-select>
			</el-form-item>
			<el-form-item label="标识属性">
				<custom-select ref="customSelectRef" :config="{ placeholder: '请设置标识属性', val: '其他筛选' }">
					<div>
						<el-table
							ref="effectAttrTable"
							size="small"
							height="270px"
							style="width: 1000px"
							:data="effectAttrTableData"
							@selection-change="selectionEffectAttr"
						>
							<el-table-column align="center" type="selection" min-width="5%"></el-table-column>
							<el-table-column align="left" prop="attrName" label="筛选条件" min-width="35%"></el-table-column>
							<el-table-column align="left" prop="" label="条件值" min-width="55%">
								<template #default="scope">
									<div v-if="scope.row.field != 'relevance' && scope.row.field != 'decode'">
										<el-radio v-model="scope.row.val" :label="1">是</el-radio>
										<el-radio v-model="scope.row.val" :label="0">否</el-radio>
									</div>
									<div v-else-if="scope.row.field == 'relevance'" v-for="(option, index) in options.relevanceEffectOptions" :key="index">
										<el-radio v-model="scope.row.re" :label="option.value"> {{ option.label }} </el-radio>
									</div>
									<div v-else-if="scope.row.field == 'decode'" v-for="(option, index) in options.decodeEffectOptions" :key="index + 1">
										<el-radio v-model="scope.row.dec" :label="option.value"> {{ option.label }} </el-radio>
									</div>
								</template>
							</el-table-column>
						</el-table>
						<hr />
						<div style="text-align: center">
							<el-button size="small" @click="$refs.customSelectRef.hideCustom()">关闭</el-button>
						</div>
					</div>
				</custom-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handlerQuery">查 询</el-button>
			</el-form-item>
			<div style="z-index: 1">
				<div class="effect-attr-selects" v-for="(option1, index) in currentEffectSelects" :key="index">
					<div v-if="option1.field != 'relevance' && option1.field != 'decode'">
						<div>
							<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
							<div style="float: left">
								<el-radio v-model="option1.val" :label="1">是</el-radio>
								<el-radio v-model="option1.val" :label="0">否</el-radio>
							</div>
						</div>
					</div>
					<div v-else-if="option1.field == 'relevance'">
						<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
						<div v-for="(option, index) in options.relevanceEffectOptions" :key="index" style="float: left">
							<el-radio v-model="option1.re" :label="option.value"> {{ option.label }} </el-radio>
						</div>
					</div>
					<div v-else-if="option1.field == 'decode'">
						<div style="float: left; line-height: 34px">{{ option1.attrName }}：</div>
						<div v-for="(option, index) in options.decodeEffectOptions" :key="index + 1" style="float: left">
							<el-radio v-model="option1.dec" :label="option.value"> {{ option.label }} </el-radio>
						</div>
					</div>
				</div>
			</div>
		</el-form>

		<!-- 数据列表 -->
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="handlerQuery"
			@currentChangeHandler="handlerQuery"
			@sortChangeHandler="handlerQuery"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="dialog.addOrUpdate.title" v-model="dialog.addOrUpdate.open" width="600px" append-to-body center>
			<el-form ref="addOrUpdateForm" :model="dialog.addOrUpdate.form" :rules="dialog.addOrUpdate.rule" label-width="120px">
				<el-form-item label="业务名称" prop="name">
					<el-input v-model="dialog.addOrUpdate.form.name" placeholder="请输入业务名称" maxlength="200"></el-input>
				</el-form-item>
				<el-form-item label="步骤设置" prop="stepSet">
					<el-select v-model="dialog.addOrUpdate.form.stepSet" placeholder="请选择步骤设置" style="width: 100%">
						<el-option v-for="(option, index) in options.stepSetOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="是否关键业务" prop="keyBusiness">
					<el-select v-model="dialog.addOrUpdate.form.keyBusiness" @change="changeKeyBusiness" placeholder="请选择是否关键业务" style="width: 100%">
						<el-option v-for="(option, index) in options.keyOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="业务展示顺序" prop="showOrder">
					<el-input-number
						v-model="dialog.addOrUpdate.form.showOrder"
						placeholder="请输入业务展示顺序"
						:disabled="addDialogForm.showOrderDisabled"
						:controls="false"
						:max="1000000"
						style="width: 100%"
					></el-input-number>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handlerSubmit" :loading="dialog.addOrUpdate.btnLoading">确 定</el-button>
				<el-button @click="closeAddOrUpdateDialog">取 消</el-button>
			</template>
		</el-dialog>

		<!-- 专属指标导入/导出弹出层 -->
		<el-dialog
			:key="importIndicatorDialogKey"
			:title="dialog.imp.title"
			v-model="dialog.imp.open"
			width="1000px"
			:close-on-click-modal="false"
			center
			@closed="importIndicatorDialogKey -= 1"
		>
			<el-form :model="impSearchFormData" :inline="true" :label-width="100">
				<el-form-item label="业务名称" prop="name">
					<el-input v-model="impSearchFormData.name" placeholder="请输入业务名称" clearable class="yd-input" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="handlerImpQuery">查 询</el-button>
				</el-form-item>
			</el-form>
			<!-- 数据列表 -->
			<el-row :gutter="10">
				<el-col :span="12">
					<el-table
						ref="impTableRef"
						stripe
						max-height="500px"
						:data="impTableData.data"
						@select="handlerImpSelection"
						@select-all="handlerImpSelectionAll"
						@row-click="handlerRowClick"
					>
						<el-table-column type="selection" width="55" align="left"></el-table-column>
						<el-table-column type="index" label="序号" width="55" align="center">
							<template #default="scope">
								<span>{{ (impSearchFormData.pageNum - 1) * impSearchFormData.pageSize + scope.$index + 1 }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="name" label="业务名称"></el-table-column>
					</el-table>
					<el-pagination
						v-show="impTableData.total > 0"
						class="yd-pagination"
						layout="total, sizes, prev, pager, next, jumper"
						v-model:current-page="impSearchFormData.pageNum"
						v-model:page-size="impSearchFormData.pageSize"
						:page-sizes="[10, 20, 30, 50, 100]"
						:total="impTableData.total"
						@size-change="handlerImpQuery"
						@current-change="handlerImpQuery"
					>
					</el-pagination>
				</el-col>
				<el-col :span="12">
					<el-table
						ref="impStepTableRef"
						stripe
						max-height="500px"
						:data="impStepTableData.data"
						@select="handlerImpStepSelection"
						@select-all="handlerImpStepSelectionAll"
					>
						<el-table-column type="selection" width="55" align="left"></el-table-column>
						<el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
						<el-table-column prop="name" label="步骤名称"></el-table-column>
					</el-table>
				</el-col>
			</el-row>
			<br />

			<div style="text-align: center">
				<el-upload
					v-if="importFlag"
					:ref="dialog.imp.ref"
					:headers="dialog.imp.headers"
					action="/admin/modules/resource/indicator/batchImport"
					:data="{ resourceCodingList: selectedImpStepCodes }"
					drag
					:auto-upload="false"
					accept=".xls,.xlsx"
					:limit="dialog.imp.limit"
					:on-exceed="handlerUploadOnExceed"
					:on-success="handlerUploadOnSuccess"
					:on-error="handlerUploadOnError"
				>
					<el-icon><Upload /></el-icon>
					<div class="el-upload_text">将文件拖到此处，或<em>点击上传</em></div>
				</el-upload>
			</div>
			<template #footer>
				<el-button type="primary" @click="downloadTemplate" v-if="importFlag">下载模板</el-button>
				<el-button type="primary" @click="handlerImport" v-if="importFlag">确 定</el-button>
				<el-button type="primary" @click="handlerExport" v-if="!importFlag">下 载</el-button>
				<el-button @click="closeImpDialog">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="BusinessConfig" lang="jsx">
import CustomSelect from '@/components/CustomSelect/index.vue';
import { synchronousBusinessOptions } from '@/utils/admin/options';
import {
	querySynchronousBusiness,
	addSynchronousBusiness,
	editSynchronousBusiness,
	deleteSynchronousBusinessByIds,
	confirmByIds,
	cancelByIds,
	importTemplate,
	queryToImport,
	download,
} from '@/api/admin/businessMonitor/businessConfig';
import { getToken } from '@/utils/auth';
import { downloadFromBlob } from '@/utils/common';
import { onActivated } from 'vue';

const { proxy } = getCurrentInstance();
const route = useRoute();

const effectAttrTableData = ref([
	{
		field: 'isStatus',
		attrName: '确认状态',
		val: 1,
		re: '0',
		dec: 'no',
	},
	{
		field: 'keyBusiness',
		attrName: '是否关键业务',
		val: 1,
		re: '0',
		dec: 'no',
	},
]);
const currentEffectSelects = ref([]);
const importFlag = ref(true);
// 导入导出选择的行数据ids
const selectedImpIds = ref([]);
// 导入导出选择的行数据
const selectedImp = ref({});
// 导入导出选择的行数据ids
const selectedImpStepCodes = ref([]);
// 导入导出选择的行数据
const selectedImpStep = ref({});
// 专属指标导入弹出层key
const importIndicatorDialogKey = ref(-1);
//枚举变量
const options = ref(synchronousBusinessOptions());
// 搜索表单数据
let searchFormData = reactive({
	...route.query,
	pageSize: 10,
	pageNum: 1,
	// 默认按启动时间降序
	orderByColumn: 'id',
	isAsc: 'desc',
	stepSet: '',
});
// 新增显示层
let addDialogForm = reactive({
	showOrderDisabled: true,
});
// 列表配置
let tableConfig = reactive({
	url: querySynchronousBusiness,
	columns: [
		{
			label: '业务名称',
			prop: 'name',
			render: (row, val) => {
				if (proxy.checkRole(['admin']) || proxy.checkPermi(['synchronousBusiness:processList'])) {
					const router = {
						path: '/admin/businessMonitor/businessStepConfig',
						query: {
							systemCode: row.systemCode,
							synchronousBusinessCode: row.resourceCoding,
						},
					};
					return (
						<router-link to={router} class="link-type">
							<span>{val}</span>
						</router-link>
					);
				}
				return <span>{val}</span>;
			},
		},
		{
			label: '业务编码',
			prop: 'resourceCoding',
			showOverFlowToolTip: true,
		},
		{
			label: '步骤设置',
			prop: 'stepSet',
			formatter: (row, val) => {
				return options.value.stepSetOptionsMap[val];
			},
		},
		{
			label: '确认状态',
			prop: 'isStatus',
			formatter: (row, val) => {
				return options.value.statusOptionsMap[val];
			},
		},
		{
			label: '确认时间',
			prop: 'confirmTime',
		},
		{
			label: '关键业务',
			prop: 'keyBusiness',
			formatter: (row, val) => {
				return options.value.keyOptionsMap[val];
			},
		},
		{
			label: '显示顺序',
			prop: 'showOrder',
			showOverFlowToolTip: true,
			sortable: true,
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['synchronousBusiness:add'], handler: () => handlerAdd() },
		{
			name: '修改',
			icon: 'yd-icon-edit',
			permi: ['synchronousBusiness:update'],
			disable: 'single',
			handler: () => handlerEdit(),
		},
		{
			name: '删除',
			icon: 'yd-icon-delete',
			permi: ['synchronousBusiness:delete'],
			disable: 'multiple',
			handler: () => handlerDelete(),
		},
		{
			name: '确认',
			icon: 'yd-icon-confirm',
			permi: ['synchronousBusiness:confirm'],
			disable: 'check',
			handler: () => handlerConfirm(),
			check: () => checkStatus(0),
		},
		{
			name: '取消',
			icon: 'yd-icon-cancel',
			permi: ['synchronousBusiness:cancel'],
			disable: 'check',
			handler: () => handlerCancel(),
			check: () => checkStatus(1),
		},
		{
			name: '导入专属指标',
			icon: 'yd-icon-import',
			permi: ['indicator:detail:import'],
			handler: () => handlerImport(),
		},
		{
			name: '导出专属指标',
			icon: 'yd-icon-export',
			permi: ['indicator:detail:export'],
			handler: () => handlerExport(),
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: true,
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
let impSearchFormData = reactive({
	pageSize: 10,
	pageNum: 1,
	// 默认按启动时间降序
	orderByColumn: 'id',
	isAsc: 'desc',
});
let impTableConfig = reactive({
	columns: [
		{
			label: '业务名称',
			prop: 'name',
		},
	],
	// 开启复选框
	enableSelection: false,
	// 开启单击事件
	rowClick: true,
	// 开启分页
	pagination: true,
	// 加载层
	loading: true,
	radioRow: {},
});
// 列表数据
let impTableData = reactive({
	data: [],
	total: 0,
});
// 列表数据
let impStepTableData = reactive({
	data: [],
	total: 0,
});
// 勾选记录
let record = reactive({
	business: {},
	step: {},
});
// 当前点击的业务项
let currentClickBusinessItem = reactive({});
// 选择的行数据ids
const selectedIds = ref([]);
// 选择的行数据
const selected = ref({});
let dialog = reactive({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
		rule: {
			name: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }],
			stepSet: [{ required: true, message: '步骤设置必选', trigger: 'change' }],
			keyBusiness: [{ required: true, message: '是否关键业务必选', trigger: 'change' }],
			showOrder: [{ validator: validateShowOrder, trigger: 'blur' }],
		},
	},
	imp: {
		// ref
		ref: 'uploadRef',
		// 打开状态
		open: false,
		// 标题
		title: '导入',
		// 上传请求头
		headers: {
			Authorization: 'Bearer ' + getToken(),
		},
		// 最多导入数
		limit: 1,
	},
});

onActivated(() => {
	if (route.query.systemCode) {
		searchFormData.systemCode = route.query.systemCode;
		handlerQuery();
	}
});

function formInited() {
	if (!route.query.systemCode) {
		handlerQuery();
	}
}
/**
 * 校验关键业务顺序
 */
function validateShowOrder(rule, value, callback) {
	if (dialog.addOrUpdate.form.keyBusiness == 1 && (!value || value == 0)) {
		callback(new Error('关键业务顺序不能为空或零'));
	} else {
		callback();
	}
}
/**
 * 关闭新增或修改弹出层
 */
function closeAddOrUpdateDialog() {
	dialog.addOrUpdate.open = false;
}

/**
 * 选择行数据
 */
function handlerSelectionChange(selects) {
	selectedIds.value = selects.map((item) => item.id);
	selected.value = selects;
}

function handlerQuery(filter) {
	queryFilter();
	if (typeof filter === 'function' && !filter()) {
		return;
	}
	tableConfig.loading = true;
	querySynchronousBusiness(searchFormData).then((res) => {
		tableConfig.loading = false;
		if (res.code !== 200) {
			return;
		}
		if (res.result !== null) {
			tableData.data = res.result.data;
			tableData.total = res.result.total;
		}
	});
}
function selectionEffectAttr(selects) {
	currentEffectSelects.value = selects;
}
function queryFilter() {
	// 关闭标识属性下拉框
	proxy.$refs.customSelectRef.hideCustom();
	// 设置查询值
	searchFormData.isSensitiveInformation = undefined;
	searchFormData.isSaveOri = undefined;
	searchFormData.isCheckAll = undefined;
	searchFormData.effectAttrList = [];
	const effectList = JSON.parse(JSON.stringify(currentEffectSelects.value));
	effectList.forEach((effect) => {
		if (effect.field === 'isSensitiveInformation') {
			searchFormData.isSensitiveInformation = effect.val;
		} else if (effect.field === 'isSaveOri') {
			searchFormData.isSaveOri = effect.val;
		} else if (effect.field === 'isCheckAll') {
			searchFormData.isCheckAll = effect.val;
		} else if (effect.field === 'relevance') {
			searchFormData.effectAttrList.push({
				likeVal: effect.field + ':' + effect.re,
			});
		} else if (effect.field === 'decode') {
			searchFormData.effectAttrList.push({
				likeVal: effect.field + ':' + effect.dec,
			});
		} else {
			searchFormData.effectAttrList.push({
				likeVal: effect.field + ':' + (effect.val === 1 ? '1' : '0'),
			});
		}
	});
	return true;
}
/**
 * 判断是否能取消与确认
 */
function checkStatus(status) {
	let flag = false;
	if (selected.value !== undefined && selected.value !== null && selected.value.length > 0) {
		selected.value.forEach((item) => {
			if (item.isStatus == status) {
				flag = true;
			}
		});
	}
	return flag;
}
/**
 * 改变是否关键业务
 */
function changeKeyBusiness(value) {
	if (value === 0) {
		dialog.addOrUpdate.form.showOrder = undefined;
		addDialogForm.showOrderDisabled = true;
	} else if (value === 1) {
		addDialogForm.showOrderDisabled = false;
	}
}
/**
 * 新增
 */
function handlerAdd() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 表单重置
		dialog.addOrUpdate.form = {};
		// 设置系统编码
		dialog.addOrUpdate.form.systemCode = searchFormData.systemCode;
		proxy.resetForm('addOrUpdateForm');
		// 标题
		dialog.addOrUpdate.title = '新增';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnLoading = true;
		addSynchronousBusiness(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnLoading = false;
			if (res.code !== 200) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('新增成功！');
		});
	});
}
/**
 * 确认
 */
function handlerConfirm() {
	proxy.$modal
		.confirm('是否确认所选项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return confirmByIds(selected.value.map((item) => item.id));
		})
		.then(() => {
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('确认成功！');
		})
		.catch(function () {});
}
/**
 * 删除
 */
function handlerDelete() {
	let dialogStr = '是否确认删除所选项?';
	for (let i = 0; i < selected.value.length; i++) {
		if (selected.value[i].stepCount > 0) {
			dialogStr = '所选业务下面有步骤，是否确认删除?';
			break;
		}
	}
	proxy.$modal
		.confirm(dialogStr, '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return deleteSynchronousBusinessByIds(selectedIds.value);
		})
		.then(() => {
			// 刷新列表 计算是否要查询上一页的数据
			if (tableData.total && searchFormData.pageSize) {
				// 删除后的总条数
				let totalCount = tableData.total - selectedIds.value.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / searchFormData.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				searchFormData.pageNum = searchFormData.pageNum > totalPage ? totalPage : searchFormData.pageNum;
			} else {
				searchFormData.pageNum = 1;
			}
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('删除成功！');
		});
}
/**
 * 修改
 */
function handlerEdit() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 数据回显，数据需要拷贝一下
		const d = JSON.parse(JSON.stringify(selected.value[0]));
		dialog.addOrUpdate.form = d;
		// 标题
		dialog.addOrUpdate.title = '修改';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		if (d.keyBusiness === 1) {
			addDialogForm.showOrderDisabled = false;
		} else {
			dialog.addOrUpdate.form.showOrder = undefined;
			addDialogForm.showOrderDisabled = true;
		}
		return;
	}
	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnDisabled = true;
		editSynchronousBusiness(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnDisabled = false;
			if (res.code !== 200) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('修改成功！');
		});
	});
}
/**
 * 取消确认
 */
function handlerCancel() {
	proxy.$modal
		.confirm('是否将所选项改为未确认状态?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return cancelByIds(selected.value.map((item) => item.id));
		})
		.then(() => {
			// 刷新列表
			searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('取消确认成功！');
		})
		.catch(() => {});
}
/**
 * 导入
 */
function handlerImport() {
	importFlag.value = true;
	// 判断窗口是否打开
	if (!dialog.imp.open) {
		impSearchFormData.name = undefined;
		record.business = {};
		record.step = {};
		selectedImpStepCodes.value = [];
		impSearchFormData.systemCode = searchFormData.systemCode;
		dialog.imp.title = '导入';
		handlerImpQuery();
		dialog.imp.open = true;
		return;
	}
	getSelectedImpStepCodes();
	if (selectedImpStepCodes.value === null || selectedImpStepCodes.value.length == 0) {
		proxy.$modal.msgError('未选择步骤，请先选择步骤');
		return;
	}
	proxy.$refs[dialog.imp.ref].submit();
}
// 下载导入模板
function downloadTemplate() {
	importTemplate().then((res) => {
		downloadFromBlob(res, '专属指标导入模板').then((o) => {
			if (!o.flag) {
				proxy.$modal.msgWarning(o.msg);
			}
		});
	});
}
// 导入成功
function handlerUploadOnSuccess(res, file, fileList) {
	if (res.code !== 200) {
		proxy.$modal.msgError(res.msg);
		return;
	}
	dialog.imp.open = false;
	proxy.$modal.msgSuccess(res.result);
}
// 导入失败
function handlerUploadOnError(err, file, fileList) {
	dialog.imp.open = true;
	proxy.$modal.msgError('导入失败');
}
// 查询业务-步骤
function handlerImpQuery() {
	impTableConfig.loading = true;
	impStepTableData.data = [];
	queryToImport(impSearchFormData).then((res) => {
		impTableConfig.loading = false;
		if (res.code !== 200) {
			return;
		}
		if (res.result !== null) {
			impTableData.data = res.result.data;
			impTableData.total = res.result.total;
		}
		// 根据记录复原业务勾选情况
		restoreBusinessSelection();
	});
}
// 记录业务勾选情况
function recordBusinessSelection(selection) {
	record.business[impSearchFormData.pageNum] = [];
	selection.forEach((s) => {
		record.business[impSearchFormData.pageNum].push(s.resourceCoding);
	});
}
// 记录指定业务勾选情况
function recordBusinessSelectionByItem(item, selected) {
	if (record.business[impSearchFormData.pageNum] === undefined) {
		record.business[impSearchFormData.pageNum] = [];
	}
	const inx = record.business[impSearchFormData.pageNum].indexOf(item.resourceCoding);
	if (selected) {
		if (inx < 0) {
			record.business[impSearchFormData.pageNum].push(item.resourceCoding);
		}
	} else {
		if (inx >= 0) {
			record.business[impSearchFormData.pageNum].splice(inx, 1);
		}
	}
}
// 记录步骤勾选情况
function recordStepSelection(selection, synchronousBusinessCode) {
	record.step[synchronousBusinessCode] = [];
	selection.forEach((s) => {
		record.step[synchronousBusinessCode].push(s.manualBusinessCode);
	});
}
// 根据记录复原业务勾选情况
function restoreBusinessSelection() {
	const businessRecord = record.business[impSearchFormData.pageNum];
	if (businessRecord === undefined || businessRecord.length <= 0) {
		return;
	}
	const businessItems = impTableData.data.filter((item) => businessRecord.indexOf(item.resourceCoding) >= 0);
	businessItems.forEach((item) => {
		proxy.$nextTick(() => {
			proxy.$refs.impTableRef.toggleRowSelection(item, true);
		});
	});
}
// 根据记录复原步骤勾选情况
function restoreStepSelection(code) {
	const stepRecord = record.step[code];
	if (stepRecord === undefined || stepRecord.length <= 0) {
		return;
	}
	const stepItems = impStepTableData.data.filter((item) => stepRecord.indexOf(item.manualBusinessCode) >= 0);
	stepItems.forEach((item) => {
		proxy.$nextTick(() => {
			proxy.$refs.impStepTableRef.toggleRowSelection(item, true);
		});
	});
}
// 勾选业务
function handlerImpSelection(selection, row) {
	// 点击业务
	handlerRowClick(row);
	// 记录业务勾选情况
	recordBusinessSelection(selection);
	const arr = selection.filter((item) => item.resourceCoding === row.resourceCoding);
	if (arr !== undefined && arr.length > 0) {
		// 勾选业务下的所有步骤
		row.businessProcessVoList.forEach((step) => {
			proxy.$nextTick(() => {
				proxy.$refs.impStepTableRef.toggleRowSelection(step, true);
			});
		});
		// 记录步骤勾选情况
		recordStepSelection(row.businessProcessVoList, row.resourceCoding);
	} else {
		// 取消勾选业务下的所有步骤
		row.businessProcessVoList.forEach((step) => {
			proxy.$nextTick(() => {
				proxy.$refs.impStepTableRef.toggleRowSelection(step, false);
			});
		});
		// 记录步骤勾选情况
		recordStepSelection([], row.resourceCoding);
	}
}
// 全勾选业务
function handlerImpSelectionAll(selection) {
	// 记录业务勾选情况
	recordBusinessSelection(selection);
	if (selection.length > 0) {
		// 全选
		selection.forEach((row) => {
			// 记录步骤勾选情况
			recordStepSelection(row.businessProcessVoList, row.resourceCoding);
		});
		// 如果当前选择的业务不为空，勾选业务下的所有步骤
		if (currentClickBusinessItem != null) {
			currentClickBusinessItem.businessProcessVoList.forEach((step) => {
				proxy.$nextTick(() => {
					proxy.$refs.impStepTableRef.toggleRowSelection(step, true);
				});
			});
		}
	} else {
		// 取消全选
		impTableData.data.forEach((row) => {
			// 记录步骤勾选情况
			recordStepSelection([], row.resourceCoding);
		});
		// 如果当前选择的业务不为空，取消勾选业务下的所有步骤
		if (currentClickBusinessItem != null) {
			currentClickBusinessItem.businessProcessVoList.forEach((step) => {
				proxy.$nextTick(() => {
					proxy.$refs.impStepTableRef.toggleRowSelection(step, false);
				});
			});
		}
	}
}
// 点击业务
function handlerRowClick(row) {
	impStepTableData.data = row.businessProcessVoList;
	// 根据记录复原步骤勾选情况
	restoreStepSelection(row.resourceCoding);
	// 设置当前点击的业务项
	currentClickBusinessItem = row;
}
// 勾选步骤
function handlerImpStepSelection(selection, row) {
	// 记录步骤勾选情况
	recordStepSelection(selection, row.synchronousBusinessCode);
	const arr = impTableData.data.filter((item) => item.resourceCoding === row.synchronousBusinessCode);
	if (selection.length <= 0) {
		// 步骤全部取消勾选，取消对应业务的勾选状态
		proxy.$refs.impTableRef.toggleRowSelection(arr[0], false);
		// 记录指定业务勾选情况
		recordBusinessSelectionByItem(arr[0], false);
	} else {
		// 勾选了至少一个业务，同时勾选对应业务
		proxy.$refs.impTableRef.toggleRowSelection(arr[0], true);
		// 记录指定业务勾选情况
		recordBusinessSelectionByItem(arr[0], true);
	}
}
// 全勾选步骤
function handlerImpStepSelectionAll(selection) {
	// 记录步骤勾选情况
	recordStepSelection(selection, currentClickBusinessItem.resourceCoding);
	if (selection.length > 0) {
		// 勾选对应业务
		proxy.$refs.impTableRef.toggleRowSelection(currentClickBusinessItem, true);
		// 记录指定业务勾选情况
		recordBusinessSelectionByItem(currentClickBusinessItem, true);
	} else {
		// 取消勾选对应业务
		proxy.$refs.impTableRef.toggleRowSelection(currentClickBusinessItem, false);
		// 记录指定业务勾选情况
		recordBusinessSelectionByItem(currentClickBusinessItem, false);
	}
}
// 表单提交
function handlerSubmit() {
	if (dialog.addOrUpdate.title === '新增') {
		handlerAdd();
	} else {
		handlerEdit();
	}
}
// 关闭导入导出页面
function closeImpDialog() {
	impStepTableData.data = [];
	dialog.imp.open = false;
}
// 导出
function handlerExport() {
	importFlag.value = false;
	// 判断窗口是否打开
	if (!dialog.imp.open) {
		record.business = {};
		record.step = {};
		impSearchFormData.name = undefined;
		selectedImpStepCodes.value = [];
		impSearchFormData.systemCode = searchFormData.systemCode;
		dialog.imp.title = '导出';
		handlerImpQuery();
		dialog.imp.open = true;
		return;
	}
	getSelectedImpStepCodes();
	if (selectedImpStepCodes.value === null || selectedImpStepCodes.value.length == 0) {
		proxy.$modal.msgError('未选择步骤，请先选择步骤');
		return;
	}
	const data = {};
	data.resourceCodingList = selectedImpStepCodes.value;
	download(data).then((res) => {
		downloadFromBlob(res, '专属指标列表').then((o) => {
			if (!o.flag) {
				proxy.$modal.msgWarning(o.msg);
			} else {
				dialog.imp.open = false;
			}
		});
	});
}
/**
 * 获取导入导出步骤编码
 */
function getSelectedImpStepCodes() {
	if (record.business !== undefined && record.business !== null) {
		for (let pageNum in record.business) {
			if (record.business[pageNum] !== undefined && record.business[pageNum].length > 0) {
				record.business[pageNum].forEach((business) => {
					if (record.step[business] !== undefined && record.step[business].length > 0) {
						record.step[business].forEach((step) => {
							if (selectedImpStepCodes.value.indexOf(step) === -1) {
								selectedImpStepCodes.value.push(step);
							}
						});
					}
				});
			}
		}
	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.effect-attr-selects {
	display: inline-block;
	margin: 2px 10px;
	padding: 0 5px;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
}
</style>
